﻿@page "/login"
@using BlazorAppAuth.Data
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies



@inject NavigationManager NavigationManager
@inject BlazorAppAuthContext DbContext

<style>
	.bg-custom {
		background-image: url('bg-custom.png');
		background-position: center center;
		background-repeat: no-repeat;
		background-size: cover;
		background-attachment: fixed;
	}
</style>

<div class="container">
	<div class="row justify-content-center align-items-center min-vh-100">
		<div class="col-8  p-0">
			<div class="card shadow">
				<div class="row g-0">
					<!-- 系统介绍部分 -->
					<div class="col-md-6 bg-custom d-flex align-items-center">
						<div class="p-5 text-white">
							<p>Web软件应用开发平台</p>
							<p>竞赛模块：模块C</p>
							<p>竞赛工位：XX号</p>
							<p>选手1姓名：XXX</p>
							<p>选手2姓名：XXX</p>
							<p>日期时间：@DateTime.Now</p>
						</div>
					</div>
					<!-- 登录表单部分 -->
					<div class="col-md-6">
						<div class="card-body p-5">
							<h4 class=" mb-4">登录</h4>
							<EditForm Model="@loginModel" OnValidSubmit="HandleLogin" FormName="login">
								<DataAnnotationsValidator />
								<div class="form-group mb-3">
									<InputText id="username" class="form-control" @bind-Value="loginModel.Name" placeholder="用户名" />
									<ValidationMessage For="@(() => loginModel.Name)" />
								</div>
								<div class="form-group mb-3">
									<InputText placeholder="密码" type="password" id="password" class="form-control" @bind-Value="loginModel.Password" />
									<ValidationMessage For="@(() => loginModel.Password)" />
								</div>
								<div class="mb-3">
									<div class="input-group">
										<InputText type="text" class="form-control" id="captcha" placeholder="验证码" @bind-Value="loginModel.CaptchaCode" required/>
										<canvas id="captcha_el" class="w-50" height="30"></canvas>
									</div>
								</div>
								<button type="submit" class="btn btn-primary w-100">登录</button>
								<div class="d-flex justify-content-between">
									<a href="/register" class="btn btn-link text-decoration-none">注册</a>
									<button class="btn btn-link text-decoration-none" @onclick="RestInfo" type="reset">重置</button>
								</div>
								@if (!string.IsNullOrEmpty(errorMessage))
								{
									<div class="alert alert-danger mt-3" role="alert">
										@errorMessage
									</div>
								}
							</EditForm>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>





@code {
	private string errorMessage = string.Empty;

	[CascadingParameter]
	public HttpContext? HttpContext { get; set; }

	[SupplyParameterFromForm]
	public LoginViewModel loginModel { get; set; } = new();

	string captcha = "_";
	string InputCaptcha = "";


	public class LoginViewModel
	{
		[Required(AllowEmptyStrings = false, ErrorMessage = "用户名不能为空")]
		public string Name { get; set; }
		[Required(AllowEmptyStrings = false, ErrorMessage = "SBSBSBS")]
		public string Password { get; set; }
		[Required(AllowEmptyStrings = false, ErrorMessage = "验证码不能为空")]
		public string CaptchaCode { get; set; }
	}

	void RestInfo()
	{
		loginModel = new();
	}

	private async Task HandleLogin()
	{
		// 这里暂时有问题，只能在server render模式下使用，但是在server 模式下又无法使用HttpContext
		// var is_valid_captcha = await js.InvokeAsync<bool>("is_valid_captcha", input_captcha);

		// if (!is_valid_captcha)
		// {
		// 	errorMessage = "验证码不正确";
		// 	StateHasChanged();
		// 	return;
		// }

		// captcha = await js.InvokeAsync<string>("get_captcha");
		var user = await DbContext.UserAccount
			.FirstOrDefaultAsync(u => u.Name == loginModel.Name && u.Password == loginModel.Password);

		if (user != null)
		{

			var claims = new List<Claim>
			{
				new Claim(ClaimTypes.Name, user.Name),
				new Claim(ClaimTypes.Role, user.Role)
			};
			var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
			var principal = new ClaimsPrincipal(identity);
			await HttpContext.SignInAsync(principal);
			// 登录成功，重定向到主页或仪表板
			NavigationManager.NavigateTo("/");
		}
		else
		{
			errorMessage = "用户名或密码错误";
		}
	}


	private void ResetForm()
	{
		loginModel = new();
		errorMessage = "";
	}

}
